package com.pango.core.interceptors;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.pango.core.security.UserContext;
import com.pango.core.security.UserDetails;
import com.pango.core.utils.StringUtils;
import com.pango.core.utils.URLUtils;
import com.pango.system.services.ResourceService;

/**
 * 用户URL访问拦截器
 * @ClassName: AuthInterceptor
 * @author thierry.fu
 * @date 2014年7月11日 下午2:18:18
 */
public class AuthInterceptor implements HandlerInterceptor{
	
	private List<String> excludeUrls;
	
	@Autowired
	private ResourceService resourceService;

	public List<String> getExcludeUrls() {
		return excludeUrls;
	}

	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		String reqPath = URLUtils.getRequestPath(request);
		String functionId = StringUtils.nilToBlank(request.getParameter("clickFunctionId"));
		
		//静态资源不做过滤
		if(reqPath.startsWith("/static")) return true;
		
		//过滤配置文件中的地址
		if(excludeUrls.contains(reqPath)) return true;
		
		//过去非菜单按钮地址
		if(functionId.length() <= 0) return true;
		
		UserDetails user = UserContext.getCurrentUser();
		List<String> resourceNames = 
		resourceService.selectResourceNamesByUserName(user.getUsername());
		
		if(resourceNames.contains(reqPath)) return true;
		
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
